import 'dart:async';
import 'package:digital/https/apiUrl.dart';
import 'package:digital/https/http.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../../common/styles.dart';
import '../../common/utils/util.dart';
import '../../provider/user_provider.dart';
import '../../router/app_router.dart';
import '../../router/router_utils.dart';
import 'model/digVideoEntity.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => IndexPageState();
}

class IndexPageState extends State<IndexPage> {
  String _selectedRole = '角色切换'; // 初始选择值
  List<DigVideoObj> _roles = [];

  loadData() async {
    EasyLoading.show();
    var res = await ApiClient().getRequest(apiUrl.getDigList);
    EasyLoading.dismiss();
    if (res["code"] == 200) {
      setState(() {
        _roles = DigVideoEntity.fromJson(res).data ?? [];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    loadData();
    // _roles = roles(context); // 初始化角色列表
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> onJoin(DigVideoObj item) async {
    await [
      Permission.microphone,
      Permission.storage,
    ].request();
    await Future.delayed(const Duration(milliseconds: 200));
    bool permissionMicrophone = await Util.requestMicrophonePermission();
    bool permissionStorage = await Util.requestStoragePermission();
    print("creationFileUrl======${item.creationFileUrl}");
    if (permissionMicrophone && permissionStorage) {
      RouterUtils.toRouter(context, RouterValues.test, arguments: {
        "label": item.creationName,
        "imagePath": item.creationFileUrl
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Consumer<UserProvider>(
        builder: (context, vm, _) {
          return Stack(
            fit: StackFit.expand,
            children: [
              // 使用图片作为背景
              Positioned.fill(
                bottom: 0,
                child: Container(
                  height: height, // 调整图片高度以适应不同设备
                  width: width,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                          'assets/images/teacher/bg.png'), // 替换为你的图片路径
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),

              // 底部图片
              Positioned(
                bottom: 0, // 将图片放在底部
                left: 0,
                right: 0,
                child: Container(
                  alignment: Alignment.center, // 居中对齐
                  child: Image.asset(
                    'assets/images/index_bg.png', // 底部图片的路径
                    fit: BoxFit.cover,
                    width: width, // 使图片宽度与屏幕宽度相同
                  ),
                ),
              ),

              // 定位角色选择下拉框
              Positioned(
                top: 62.w, // 从顶部偏移
                left: 0,
                right: 0, // 添加这一行以实现水平居中
                child: _changeText(context, vm),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _changeText(BuildContext context, UserProvider vm) {
    return GestureDetector(
      onTap: () {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('角色切换'),
              content: DropdownButton<DigVideoObj>(
                value: _roles.firstWhere(
                    (item) => item.creationId == _selectedRole,
                    orElse: () => _roles.first),
                hint: const Text('角色切换'),
                onChanged: (DigVideoObj? newValue) {
                  if (newValue != null) {
                    // 添加检查以避免使用 null
                    setState(() {
                      _selectedRole = newValue.creationName ?? "";
                      Navigator.of(context).pop(); // 先关闭弹框
                    });

                    // 在 setState 外部调用 onJoin
                    onJoin(newValue);
                  }
                },
                items: _roles.map((DigVideoObj value) {
                  return DropdownMenuItem<DigVideoObj>(
                    value: value,
                    child: Text(value.creationName ?? ""),
                  );
                }).toList(),
              ),
            );
          },
        );
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Row(
          mainAxisSize: MainAxisSize.min, // 只分配必要的宽度
          mainAxisAlignment: MainAxisAlignment.center, // 水平方向居中对齐
          children: [
            Text(
              _selectedRole,
              style: TextStyle(
                  fontSize: 18.sp,
                  color: Styles.black3Color,
                  fontWeight: FontWeight.bold),
            ),
            Image.asset(
              "assets/images/roleChange.png",
              width: 16.w,
              fit: BoxFit.cover,
            ),
          ],
        ),
      ),
    );
  }
}
